﻿using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using jnagr.DBUtility;//Please add references
namespace jnagr.DAL
{
    /// <summary>
    /// 数据访问类:pdatainfo
    /// </summary>
    public partial class pdatainfo
    {
        public pdatainfo()
        { }
        #region  BasicMethod

        /// <summary>
        /// 得到最大ID
        /// </summary>
        public int GetMaxId()
        {
            return DbHelperSQL.GetMaxID("pdid", "pdatainfo");
        }
        public int updateCBDhw(string pdid, string devid,DataSet ds,int plantid,int uid,string pro)
        {
            int im = 0;
            string[] ids = pdid.Split(',');
            foreach (string id in ids)
            {
                int idint = 0,petid=0;
                int.TryParse(id, out idint);
                if (idint == 0) continue;
                DAL.devinfo dal = new devinfo();
                Model.pdatainfo pm = GetModel(idint);
                if (pm.Isrengong != 1)
                {
                   Model.ForestPets m=new Model.ForestPets();
                    m.address = pro;
                    if (pm.pdate != null)
                        m.inputTime = pm.pdate;
                    else
                        m.inputTime = DateTime.Now;
                    m.plantsId = plantid;
                    m.toolsNums = devid;
                    m.uid = uid;
                    petid = 0;
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (ds.Tables[0].Rows[i]["hname"].ToString() == pm.pname)
                        {
                            int.TryParse(ds.Tables[0].Rows[i]["mhid"].ToString(), out petid);
                        }

                    }
                    if (petid == 0) continue;
                    m.petsId = petid;
                    m.investigationMethod = "图像自动识别";
                    m.petStage = "成虫";
                    m.totalUnit= "成虫";
                    m.monitorWay = "测报灯";
                    m.femaleNums = pm.pnum.ToString();
                    m.maleNums = "0";
                    m.totalCount = pm.pnum.ToString();
                    DAL.ForestPets fb = new ForestPets();
                    fb.Add(m);
                    pm.Isrengong = 1;
                    Updateis(pm);
                    im = 1;
                }                
            }
            return im;

        }
        public int updateYBQhw(string pdid, string devid, string ptstr, DateTime dt, int l)
        {
            int i = 0;

            //SELECT TOP 1 [keyid],[devID],[ch0],[ch1],[ch2],[ch3],[updateTime] FROM[dbstatus].[dbo].[t_ybqstatus] where 1=1 and abs(datediff(ss,'2014-11-08 19:26:16.000', updateTime))<15*60 order by abs(datediff(ss,'2014-11-08 19:26:16.000', updateTime))
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT TOP 1 [keyid],[devID],[ch0],[ch1],[ch2],[ch3],[updateTime] FROM [dbstatus].[dbo].[t_ybqstatus] where devID=@devID and abs(datediff(ss,@date, updateTime))<@l*60 order by abs(datediff(ss,@date, updateTime))");

            SqlParameter[] parameters = {
                new SqlParameter("@devID", SqlDbType.NVarChar,20),
                    new SqlParameter("@date", SqlDbType.SmallDateTime),
                    new SqlParameter("@l", SqlDbType.Int,4)
            };
            parameters[0].Value = devid;
            parameters[1].Value = dt;
            parameters[2].Value = l;
            DataSet ds = null;
            try
            {
                DbHelperSQL.connectionString = PubConstant.GetConnectionString("weatheruser");
                ds = DbHelperSQL.Query(strSql.ToString(), parameters);
                DbHelperSQL.connectionString = PubConstant.ConnectionString;
                if (ds != null && ds.Tables[0].Rows.Count == 1)
                {
                    int keyid = 0;
                    int.TryParse(ds.Tables[0].Rows[0]["keyid"].ToString(), out keyid);
                    if (keyid == 0)
                    {
                        return 0;
                    }
                    string[] ids = pdid.Split(',');
                    foreach (string id in ids)
                    {
                        int idint = 0;
                        int.TryParse(id, out idint);
                        if (idint == 0) continue;
                        DAL.devinfo dal = new devinfo();
                        Model.devinfo m = dal.GetModel(devid, "YBQ");
                        Model.pdatainfo pm = GetModel(idint);
                        if (m.chn0 != "")
                        {
                            if (pm.pname == m.chn0)
                            {
                                string sql = "update [dbstatus].[dbo].[t_ybqstatus] set [ch0]=" + pm.pnum + " where keyid=" + keyid;
                                DbHelperSQL.ExecuteSql(sql);
                            }
                        }
                        if (m.chn1 != "")
                        {
                            if (pm.pname == m.chn1)
                            {
                                string sql = "update [dbstatus].[dbo].[t_ybqstatus] set [ch1]=" + pm.pnum + " where keyid=" + keyid;
                                DbHelperSQL.ExecuteSql(sql);
                            }
                        }
                        if (m.chn2 != "")
                        {
                            if (pm.pname == m.chn2)
                            {
                                string sql = "update [dbstatus].[dbo].[t_ybqstatus] set [ch2]=" + pm.pnum + " where keyid=" + keyid;
                                DbHelperSQL.ExecuteSql(sql);
                            }
                        }
                        if (m.chn3 != "")
                        {
                            if (pm.pname == m.chn3)
                            {
                                string sql = "update [dbstatus].[dbo].[t_ybqstatus] set [ch3]=" + pm.pnum + " where keyid=" + keyid;
                                DbHelperSQL.ExecuteSql(sql);
                            }
                        }
                        i = 1;
                    }

                }

            }
            catch (Exception ex)
            {
                i = 0;
            }
            finally
            {
                DbHelperSQL.connectionString = PubConstant.ConnectionString;
            }

            return i;

        }
        public int getYBQhw(string devid, string ptstr, DateTime dt, int l)
        {
            int i = 0;

            //SELECT TOP 1 [keyid],[devID],[ch0],[ch1],[ch2],[ch3],[updateTime] FROM[dbstatus].[dbo].[t_ybqstatus] where 1=1 and abs(datediff(ss,'2014-11-08 19:26:16.000', updateTime))<15*60 order by abs(datediff(ss,'2014-11-08 19:26:16.000', updateTime))
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT TOP 1 [keyid],[devID],[ch0],[ch1],[ch2],[ch3],[updateTime] FROM [dbstatus].[dbo].[t_ybqstatus] where devID=@devID and abs(datediff(ss,@date, updateTime))<@l*60 order by abs(datediff(ss,@date, updateTime))");

            SqlParameter[] parameters = {
                new SqlParameter("@devID", SqlDbType.NVarChar,20),
                    new SqlParameter("@date", SqlDbType.SmallDateTime),
                    new SqlParameter("@l", SqlDbType.Int,4)
            };
            parameters[0].Value = devid;
            parameters[1].Value = dt;
            parameters[2].Value = l;
            //DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            DataSet ds = null;
            try
            {
                DbHelperSQL.connectionString = PubConstant.GetConnectionString("weatheruser");
                ds = DbHelperSQL.Query(strSql.ToString(), parameters);
                DbHelperSQL.connectionString = PubConstant.ConnectionString;
                if (ds != null && ds.Tables[0].Rows.Count == 1)
                {
                    int pid = 0;
                    string sql = "select pid from uppicsinfo where ptstr='" + ptstr + "'";
                    object o = DbHelperSQLPIC.GetSingle(sql);
                    if (o == null)
                    {
                        return 0;
                    }
                    else
                    {
                        int.TryParse(o.ToString(), out pid);
                        if (pid == 0) return 0;
                    }
                    DAL.devinfo dal = new devinfo();
                    Model.devinfo m = dal.GetModel(devid, "YBQ");
                    DateTime dtm;
                    Model.pdatainfo p = new Model.pdatainfo();
                    DateTime.TryParse(ds.Tables[0].Rows[0]["updateTime"].ToString(), out dtm);
                    p.pdate = dtm;
                    p.pmark = ptstr;
                    if (m.chn0 != "")
                    {
                        p.pname = m.chn0;
                        int ch0 = 0;
                        int.TryParse(ds.Tables[0].Rows[0]["ch0"].ToString(), out ch0);
                        p.pnum = ch0;
                        Add(p);
                    }
                    if (m.chn1 != "")
                    {
                        p.pname = m.chn1;
                        int ch0 = 0;
                        int.TryParse(ds.Tables[0].Rows[0]["ch1"].ToString(), out ch0);
                        p.pnum = ch0;
                        Add(p);
                    }
                    if (m.chn2 != "")
                    {
                        p.pname = m.chn2;
                        int ch0 = 0;
                        int.TryParse(ds.Tables[0].Rows[0]["ch2"].ToString(), out ch0);
                        p.pnum = ch0;
                        Add(p);
                    }
                    if (m.chn3 != "")
                    {
                        p.pname = m.chn3;
                        int ch0 = 0;
                        int.TryParse(ds.Tables[0].Rows[0]["ch3"].ToString(), out ch0);
                        p.pnum = ch0;
                        Add(p);
                    }
                    i = 1;
                }

            }
            catch (Exception ex)
            {
                i = 0;
            }
            finally
            {
                DbHelperSQL.connectionString = PubConstant.ConnectionString;
            }

            return i;

        }
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int pdid)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from pdatainfo");
            strSql.Append(" where pdid=@pdid");
            SqlParameter[] parameters = {
                    new SqlParameter("@pdid", SqlDbType.Int,4)
            };
            parameters[0].Value = pdid;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }


        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(jnagr.Model.pdatainfo model)
        {
            int pid = 0;
            string sql = "select pid from uppicsinfo where ptstr='" + model.pmark + "'";
            object o = DbHelperSQLPIC.GetSingle(sql);
            if (o == null)
            {
                return 0;
            }
            else
            {
                int.TryParse(o.ToString(), out pid);
                if (pid == 0) return 0;
            }
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into pdatainfo(");
            strSql.Append("pid,pname,pnum,pdate,pmark)");
            strSql.Append(" values (");
            strSql.Append("@pid,@pname,@pnum,@pdate,@pmark)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
                    new SqlParameter("@pid", SqlDbType.Int,4),
                    new SqlParameter("@pname", SqlDbType.NVarChar,20),
                    new SqlParameter("@pnum", SqlDbType.Int,4),
                    new SqlParameter("@pdate", SqlDbType.DateTime),
                    new SqlParameter("@pmark", SqlDbType.NVarChar,200)};
            parameters[0].Value = pid;
            parameters[1].Value = model.pname;
            parameters[2].Value = model.pnum;
            parameters[3].Value = model.pdate;
            parameters[4].Value = model.pmark;

            object obj = DbHelperSQLPIC.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(jnagr.Model.pdatainfo model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update pdatainfo set ");
            strSql.Append("pname=@pname,");
            strSql.Append("pnum=@pnum");
            strSql.Append(" where pdid=@pdid");
            SqlParameter[] parameters = {

                    new SqlParameter("@pname", SqlDbType.NVarChar,20),
                    new SqlParameter("@pnum", SqlDbType.Int,4),
                    new SqlParameter("@pdid", SqlDbType.Int,4)};
            parameters[0].Value = model.pname;
            parameters[1].Value = model.pnum;
            parameters[2].Value = model.pdid;


            int rows = DbHelperSQLPIC.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public bool Updateis(jnagr.Model.pdatainfo model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update pdatainfo set ");
            strSql.Append("isrengong=@isrengong");           
            strSql.Append(" where pdid=@pdid");
            SqlParameter[] parameters = {

                    new SqlParameter("@isrengong", SqlDbType.Int,4),                    
                    new SqlParameter("@pdid", SqlDbType.Int,4)};
            parameters[0].Value = model.Isrengong;
            parameters[1].Value =  model.pdid;


            int rows = DbHelperSQLPIC.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int pdid)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from pdatainfo ");
            strSql.Append(" where pdid=@pdid");
            SqlParameter[] parameters = {
                    new SqlParameter("@pdid", SqlDbType.Int,4)
            };
            parameters[0].Value = pdid;

            int rows = DbHelperSQLPIC.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string pdidlist)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from pdatainfo ");
            strSql.Append(" where pdid in (" + pdidlist + ")  ");
            int rows = DbHelperSQL.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public jnagr.Model.pdatainfo GetModel(int pdid)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 pdid,pid,pname,pnum,pdate,pmark,isrengong from [jnpicDB].[dbo].pdatainfo ");
            strSql.Append(" where pdid=@pdid");
            SqlParameter[] parameters = {
                    new SqlParameter("@pdid", SqlDbType.Int,4)
            };
            parameters[0].Value = pdid;

            jnagr.Model.pdatainfo model = new jnagr.Model.pdatainfo();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public jnagr.Model.pdatainfo DataRowToModel(DataRow row)
        {
            jnagr.Model.pdatainfo model = new jnagr.Model.pdatainfo();
            if (row != null)
            {
                if (row["pdid"] != null && row["pdid"].ToString() != "")
                {
                    model.pdid = int.Parse(row["pdid"].ToString());
                }
                if (row["pid"] != null && row["pid"].ToString() != "")
                {
                    model.pid = int.Parse(row["pid"].ToString());
                }
                if (row["pname"] != null)
                {
                    model.pname = row["pname"].ToString();
                }
                if (row["pnum"] != null && row["pnum"].ToString() != "")
                {
                    model.pnum = int.Parse(row["pnum"].ToString());
                }
                if (row["pdate"] != null && row["pdate"].ToString() != "")
                {
                    model.pdate = DateTime.Parse(row["pdate"].ToString());
                }
                if (row["pmark"] != null)
                {
                    model.pmark = row["pmark"].ToString();
                }
                if (row["isrengong"] != null && row["isrengong"].ToString() != "")
                {
                    model.Isrengong = int.Parse(row["isrengong"].ToString());
                }
            }
            return model;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select pdid,pid,pname,pnum,pdate,pmark ");
            strSql.Append(" FROM pdatainfo ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataSet GetList(int Top, string strWhere, string filedOrder)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ");
            if (Top > 0)
            {
                strSql.Append(" top " + Top.ToString());
            }
            strSql.Append(" pdid,pid,pname,pnum,pdate,pmark ");
            strSql.Append(" FROM pdatainfo ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            strSql.Append(" order by " + filedOrder);
            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GetRecordCount(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM Vpdatainfo ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            object obj = DbHelperSQL.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby);
            }
            else
            {
                strSql.Append("order by T.pdid desc");
            }
            strSql.Append(")AS Row, T.*  from Vpdatainfo T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE " + strWhere);
            }
            strSql.Append(" ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            return DbHelperSQL.Query(strSql.ToString());
        }
        public int GetRecordCountp(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM Vuppicsinfo ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            object obj = DbHelperSQL.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        public DataSet GetListByPagep(string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby);
            }
            else
            {
                strSql.Append("order by T.uptime desc");
            }
            strSql.Append(")AS Row, T.*  from Vuppicsinfo T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE " + strWhere);
            }
            strSql.Append(" ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            return DbHelperSQL.Query(strSql.ToString());
        }

        /*
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetList(int PageSize,int PageIndex,string strWhere)
		{
			SqlParameter[] parameters = {
					new SqlParameter("@tblName", SqlDbType.VarChar, 255),
					new SqlParameter("@fldName", SqlDbType.VarChar, 255),
					new SqlParameter("@PageSize", SqlDbType.Int),
					new SqlParameter("@PageIndex", SqlDbType.Int),
					new SqlParameter("@IsReCount", SqlDbType.Bit),
					new SqlParameter("@OrderType", SqlDbType.Bit),
					new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
					};
			parameters[0].Value = "pdatainfo";
			parameters[1].Value = "pdid";
			parameters[2].Value = PageSize;
			parameters[3].Value = PageIndex;
			parameters[4].Value = 0;
			parameters[5].Value = 0;
			parameters[6].Value = strWhere;	
			return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
		}*/

        #endregion  BasicMethod
        #region  ExtensionMethod

        #endregion  ExtensionMethod
    }
}

